<?php
namespace Tbf\Bundle\JpushBundle;

use Guzzle\Http\Client;
use Tbf\Component\Arrays\ArrayFunction;
use Tbf\Component\Http\Ajax;

class JpushManager implements JpushManagerInterface
{
    protected $app_key;
    protected $master_secret;
    protected $api_url = 'https://api.jpush.cn:443/sendmsg/v2/sendmsg';
    protected $ajax_obj;
    public function __construct($app_key,$master_secret,Client $client)
    {
        $this->app_key = $app_key;
        $this->master_secret = $master_secret;
        $this->ajax_obj = new Ajax($client);
    }

    /**
     * 给所有人发送一条内容为xxx的消息
     * @param  int         $send_no 发送id一定时间内不要重复
     * @param  string      $content
     * @return null|string error
     */
    public function sendToAllSimple($send_no,$content)
    {
        $m = new Message();
        $m->setSendno($send_no);
        $m->setMsgContent($content);
        $m->sendToAll();

        return $this->send($m);
    }
    /**
     * @param  Message     $m
     * @return null|string error
     */
    public function send(Message $m)
    {
        $code = $m->getSendno().$m->getReceiverType().$m->getReceiverValue().$this->master_secret;
        $code = md5($code);
        $data = ArrayFunction::removeNullValue(array(
            'sendno'=>$m->getSendno(),
            'app_key'=>$this->app_key,
            'receiver_type'=>$m->getReceiverType(),
            'receiver_value'=>$m->getReceiverValue(),
            'verification_code'=>$code,
            'msg_type'=>$m->getMsgType(),
            'msg_content'=>json_encode(ArrayFunction::removeNullValue(array(
                    'n_title'=>$m->getMsgTitle(),
                    'n_content'=>$m->getMsgContent(),
                    'n_extras'=>$m->getMsgExtras(),
                ))),
            'platform'=>implode(',',$m->getPlatforms()),
            'time_to_live'=>$m->getTimeToLive()
        ));
        $response = $this->ajax_obj->request(array(
            'url'=>$this->api_url,
            'method'=>'POST',
            'data'=>$data,
            'throw'=>false,
            'return'=>'response',
        ));
        if ($response->getStatusCode()===503) {
            return 'jpush_fail!! too fast push to all user';
        }
        if ($response->getStatusCode()!==200) {
            return 'jpush_fail!! http code:'.$response->getStatusCode();
        }
        $ret = json_decode($response->getBody(true),true);
        if ($ret['errcode']===0) {
            return null;
        }

        return 'jpush_fail!! msg:'.$ret['errmsg'].' code:'.$ret['errcode'];
    }
}
